let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');

let indexRouter = require('./routes/index');
let goodsRoute = require('./routes/GoodsRoute');
let loginRoute = require('./routes/LoginRoute')
let shoppingRoute =  require('./routes/ShoppingRoute')
let starRoute =  require('./routes/StarRoute');
let goodsByStoreRoute = require('./routes/GoodsByStoreRoute');
let shoppingcardRoute = require('./routes/ShoppingRoute');
let userRoute = require('./routes/UserRoute');
let allBuyRoute = require('./routes/AllBuyRoute');
let ordersRoute = require('./routes/OrdersRoute');

let app = express();
//处理跨域
let cors = require('cors')
app.use(cors())

//1.导入用于生成jwt字符串的包token
let jwt = require("jsonwebtoken");
//2.导入用于将客户端发送过来的jwt字符串，解析还原成json对象的包
let expressJWT = require("express-jwt");
//3.secret 一个密钥字符串
const secretKey = "shopping key";
//挂载全局，方便其他router使用
app.locals.jwt = jwt;
app.locals.expressJWT = expressJWT;
app.locals.secretKey = secretKey;

//token验证中间件，如果请求中没有token信息也不通过。 unless:白名单
app.use(expressJWT({ secret:secretKey,algorithms:['HS256']}).unless({path: ['/api/login.do',"/api/logout.do"]}));

app.use(logger('dev'));
//配置接收json格式的参数,即req.body可以接收json格式的参数
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//中间件，统一处理打印及分页插件，必须写在路由之前
const pager = require("./util/PagerHelper.js")
app.use( (req,res,next)=> {
  let {pageNum, pageSize} = req.query;
  console.log("pageNum:" + pageNum,"pageSize:" + pageSize);
  if (pageNum && pageNum.trim().length > 0) {
    pager.pageNum = parseInt(pageNum);
  }
  if (pageSize && pageSize.trim().length > 0) {
    pager.pageSize = parseInt(pageSize);
  }
  next();
})

app.use('/', indexRouter);
app.use('/api/', goodsRoute);
app.use('/api/',loginRoute);
app.use('/api/shoppingcard',shoppingRoute);
app.use('/api/star',starRoute);
app.use('/api/store',goodsByStoreRoute);
app.use('/api/',loginRoute);
app.use('/api/user', userRoute);
app.use('/api/allBuy', allBuyRoute);
app.use('/api/orders', ordersRoute);

// error handler
app.use(function(err, req, res, next) {
  console.log(err);
  err.msg = "未知错误";
  res.json(err);
});

let port = 8081;
app.listen(port,() => {
  console.log(`服务已启动，http://localhost:${port}`);
})

module.exports = app;
